package com.xyht.medicine_management_system.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.medicine_management_system.auth.util.JwtTokenUtil;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.common.util.CacheUtil;
import com.xyht.medicine_management_system.modules.user.entity.*;
import com.xyht.medicine_management_system.modules.user.entity.req.*;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsRoleResp;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsUserExamineResp;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsUserResp;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsUserinfoResp;
import com.xyht.medicine_management_system.modules.user.mapper.MmsRoleMapper;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserExamineMapper;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserMapper;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserRoleRelationMapper;
import com.xyht.medicine_management_system.modules.user.service.MmsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.medicine_management_system.modules.user.util.FormatUtil;
import com.xyht.medicine_management_system.modules.user.util.InvitationCodeUtil;
import com.xyht.medicine_management_system.modules.user.util.SMSUtil;
import com.xyht.medicine_management_system.modules.user.util.verify_code.RandomUtils;
import com.xyht.medicine_management_system.modules.user.util.verify_code.VerifyCodeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.medicine_management_system.modules.user.constant.AuthStatusConstant.AUTH_STATUS_AUTH;
import static com.xyht.medicine_management_system.modules.user.constant.AuthStatusConstant.AUTH_STATUS_NOT_AUTH;
import static com.xyht.medicine_management_system.modules.user.constant.CommonConstant.*;
import static com.xyht.medicine_management_system.modules.user.constant.IsAuthConstant.IS_AUTH_FALSE;
import static com.xyht.medicine_management_system.modules.user.constant.LoginFlagConstant.LOGIN_FLAG_APP;
import static com.xyht.medicine_management_system.modules.user.constant.LoginFlagConstant.LOGIN_FLAG_BACK;
import static com.xyht.medicine_management_system.modules.user.constant.QualificationTypeConstant.QUALIFICATION_TYPE_NONE;
import static com.xyht.medicine_management_system.modules.user.constant.RoleBindStatusConstant.ROLE_BIND_ADD;
import static com.xyht.medicine_management_system.modules.user.constant.RoleBindStatusConstant.ROLE_BIND_DELETE;
import static com.xyht.medicine_management_system.modules.user.constant.UserTypeConstant.USER_TYPE_ADMIN;
import static com.xyht.medicine_management_system.modules.user.constant.UserTypeConstant.USER_TYPE_NORMAL;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-11-12
 */
@Service
public class MmsUserServiceImpl extends ServiceImpl<MmsUserMapper, MmsUser> implements MmsUserService {
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private CacheUtil cacheUtil;
    @Resource
    private MmsUserMapper mmsUserMapper;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private SMSUtil smsUtil;
    @Resource
    private MmsUserExamineMapper mmsUserExamineMapper;
    @Resource
    private MmsUserRoleRelationMapper mmsUserRoleRelationMapper;
    @Resource
    private MmsRoleMapper mmsRoleMapper;
    @Resource
    private InvitationCodeUtil invitationCodeUtil;

    @Override
    public ResponseResult webLogin(SmsUserLoginReq smsUserLoginReq) {
        if (isNullOrEmpty(smsUserLoginReq.getLoginName()) || isNullOrEmpty(smsUserLoginReq.getPassword())
                || isNullOrEmpty(smsUserLoginReq.getCode()) || isNullOrEmpty(smsUserLoginReq.getUid())
                || isNullOrEmpty(smsUserLoginReq.getLoginFlag())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        String code = smsUserLoginReq.getCode().toUpperCase();
        String uid = smsUserLoginReq.getUid();
        //验证码校验
        String cacheCode = cacheUtil.getObject(uid, String.class);
        if (cacheCode == null || !cacheCode.equals(code)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        //账号密码校验
        QueryWrapper<MmsUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda()
                .eq(MmsUser::getUsername, smsUserLoginReq.getLoginName())
                .or()
                .eq(MmsUser::getTel, smsUserLoginReq.getLoginName());
        List<MmsUser> smsUserList = mmsUserMapper.selectList(userQueryWrapper);
        if (smsUserList == null || smsUserList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        if (smsUserList.size() > 1) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_ERR);
        }
        MmsUser mmsUser = smsUserList.get(0);
        //校验登录标志
        if (smsUserLoginReq.getLoginFlag().equals(LOGIN_FLAG_BACK)) {
            if (!mmsUser.getUserType().equals(USER_TYPE_ADMIN)) {
                return CommonResult.failed(CommonCodeEnum.USER_LOGIN_FLAG_ERR);
            }
        }

        //校验密码
        if (!mmsUser.getPassword().equals(smsUserLoginReq.getPassword())) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        MmsUserResp mmsUserResp = new MmsUserResp();
        BeanUtils.copyProperties(mmsUser, mmsUserResp);
//        //校验是否认证
//        if (!mmsUser.getAuthStatus().equals(AUTH_STATUS_AUTH)){
//            return CommonResult.success(mmsUserResp);
//        }

        //缓存用户权限
//        cacheUtil.saveUserAuthorization(smsUser.getId());

        String token = jwtTokenUtil.generateToken(mmsUser.getId());
        mmsUserResp.setToken(token);
        mmsUserResp.setTokenHead(tokenHead);
        return CommonResult.success(mmsUserResp);
    }

    @Override
    public ResponseResult phoneLogin(SmsUserLoginReq smsUserLoginReq) {
        if (isNullOrEmpty(smsUserLoginReq.getCheckCode(), smsUserLoginReq.getLoginName()
                , smsUserLoginReq.getLoginFlag())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String codeTel = "CP_" + smsUserLoginReq.getLoginName();
        //TODO 对比code VERIFY_CODE_CHECK_FAIL
        String resultCode = cacheUtil.getObject(codeTel, String.class);
        if (resultCode == null || !resultCode.equals(smsUserLoginReq.getCheckCode())) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }
        //清除已使用验证码
        cacheUtil.delete(codeTel);

        List<MmsUser> userList = mmsUserMapper.selectList(new QueryWrapper<MmsUser>()
                .lambda().eq(MmsUser::getTel, smsUserLoginReq.getLoginName()));
        if (userList == null || userList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
        }

        MmsUser mmsUser = userList.get(0);
        //校验登录标志
        if (smsUserLoginReq.getLoginFlag().equals(LOGIN_FLAG_BACK)) {
            if (!mmsUser.getUserType().equals(USER_TYPE_ADMIN)) {
                return CommonResult.failed(CommonCodeEnum.USER_LOGIN_FLAG_ERR);
            }
        }

        MmsUserResp mmsUserResp = new MmsUserResp();
        BeanUtils.copyProperties(mmsUser, mmsUserResp);
//        //校验是否认证
//        if (!mmsUser.getAuthStatus().equals(AUTH_STATUS_AUTH)){
//            return CommonResult.success(mmsUserResp);
//        }

        //缓存用户权限
//        cacheUtil.saveUserAuthorization(smsUser.getId());

        String token = jwtTokenUtil.generateToken(mmsUser.getId());
        mmsUserResp.setToken(token);
        mmsUserResp.setTokenHead(tokenHead);
        return CommonResult.success(mmsUserResp);
    }

    @Override
    public ResponseResult phoneVerifyCode(String phoneNum) {
        //TODO 1分钟内同个手机号不能再次发送
        if (isNullOrEmpty(phoneNum)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (!FormatUtil.phoneFormat(phoneNum)) {
            return CommonResult.failed(CommonCodeEnum.TEL_FORMAT_ERROR);
        }
        String checkTel = "CP_" + phoneNum;
        if (cacheUtil.hasKey(checkTel)) {
            return CommonResult.failed(CommonCodeEnum.CODE_GET_FAIL);
        }

//        List<MmsUser> userList = mmsUserMapper.selectList(new QueryWrapper<MmsUser>()
//                .lambda().eq(MmsUser::getTel, phoneNum));
//        if (userList == null || userList.size() < 1) {
//            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
//        }
        VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil();
        VerifyCode verifyCode = verifyCodeUtil.generateStr(80, 28);
        String code = verifyCode.getCode();
        //TODO 发送短信 保存code
        try {
            Boolean bl = smsUtil.sendSMSCode(phoneNum, code);
            if (!bl) {
                return CommonResult.failed(CommonCodeEnum.CODE_OVERFLOW);
            }
            cacheUtil.add(checkTel, code, 1, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult findPassword(FindPasswordReq findPasswordReq) {
        if (isNullOrEmpty(findPasswordReq.getCheckCode(), findPasswordReq.getPhoneNum(), findPasswordReq.getNewPassword())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String codeTel = "CP_" + findPasswordReq.getPhoneNum();
        //TODO 对比code VERIFY_CODE_CHECK_FAIL
        String resultCode = cacheUtil.getObject(codeTel, String.class);
        if (resultCode == null || !resultCode.equals(findPasswordReq.getCheckCode())) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }
        //清除已使用验证码
        cacheUtil.delete(codeTel);

        List<MmsUser> userList = mmsUserMapper.selectList(new QueryWrapper<MmsUser>()
                .lambda().eq(MmsUser::getTel, findPasswordReq.getPhoneNum()));
        if (userList == null || userList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
        }

        MmsUser smsUser = new MmsUser();
        smsUser.setPassword(findPasswordReq.getNewPassword());
        smsUser.setId(userList.get(0).getId());
        int result = mmsUserMapper.updateById(smsUser);
        if (result == 0) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult checkUserExist(SmsUserLoginReq smsUserLoginReq) {
        if (isNullOrEmpty(smsUserLoginReq.getLoginName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        List<MmsUser> userList = mmsUserMapper.selectList(new QueryWrapper<MmsUser>()
                .lambda()
                .eq(MmsUser::getTel, smsUserLoginReq.getLoginName())
                .or()
                .eq(MmsUser::getUsername, smsUserLoginReq.getLoginName()));
        if (userList == null || userList.size() < 1) {
            return CommonResult.success(false);
        }
        if (userList.size() > 1) {
            return CommonResult.success(false);
        }
        return CommonResult.success(true);
    }

    @Override
    public ResponseResult userChangePasswordByOldPassword(String user_id, ChangeUserPassword changeUserPassword) {
        if (isNullOrEmpty(changeUserPassword.getNew_password()) || isNullOrEmpty(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (changeUserPassword.getNew_password().equals(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.OLD_PASSWORD_LIKE_NEW_PASSWORD);
        }
        MmsUser smsUser = mmsUserMapper.selectById(user_id);
        if (smsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        if (!smsUser.getPassword().equals(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.OLD_PASSWORD_ERROR);
        }

        MmsUser newUser = new MmsUser();
        newUser.setId(user_id);
        newUser.setPassword(changeUserPassword.getNew_password());
        int result = mmsUserMapper.updateById(newUser);
        if (result == 0) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult userRegister(SmsUserRegisterReq registerReq) {
        if (isNullOrEmpty(registerReq.getUsername(), registerReq.getTel(),
                registerReq.getPassword(), registerReq.getCheckCode())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //检验用户邀请码
        if (!isNullOrEmpty(registerReq.getOtherInvitationCode())){
            MmsUser mmsUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                    .eq(MmsUser::getInvitationCode,registerReq.getOtherInvitationCode()));
            if (mmsUser == null){
                return CommonResult.failed(CommonCodeEnum.USER_INVITATION_CODE_NOT_EXIST);
            }
        }

        String checkTel = "CP_" + registerReq.getTel();
        if (!cacheUtil.hasKey(checkTel)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        String code = cacheUtil.getObject(checkTel, String.class);
        if (!registerReq.getCheckCode().equals(code)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        MmsUser usernameUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .and(wrapper -> {
                    wrapper.eq(MmsUser::getUsername, registerReq.getUsername())
                            .or()
                            .eq(MmsUser::getUsername, USER_DEFAULT_TEXT + registerReq.getTel());
                }));
        if (usernameUser != null) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_EXIST);
        }

        MmsUser telUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .eq(MmsUser::getTel, registerReq.getTel()));
        if (telUser != null) {
            return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
        }

        MmsUser addUser = new MmsUser();
        addUser.setUserType(USER_TYPE_NORMAL);
        addUser.setTel(registerReq.getTel());
        addUser.setPassword(registerReq.getPassword());
        addUser.setUsername(registerReq.getUsername());
        addUser.setAuthStatus(AUTH_STATUS_NOT_AUTH);
        addUser.setQualificationType(QUALIFICATION_TYPE_NONE);
        addUser.setNickName(USER_DEFAULT_NICK_NAME);
        addUser.setOtherInvitationCode(registerReq.getOtherInvitationCode());

        mmsUserMapper.insert(addUser);

        MmsUserResp mmsUserResp = new MmsUserResp();
        BeanUtils.copyProperties(addUser, mmsUserResp);
        String token = jwtTokenUtil.generateToken(addUser.getId());
        mmsUserResp.setToken(token);
        mmsUserResp.setTokenHead(tokenHead);
        return CommonResult.success(mmsUserResp);
    }

    @Override
    public ResponseResult userPhoneRegister(SmsUserRegisterReq registerReq) {
        if (isNullOrEmpty(registerReq.getTel(), registerReq.getCheckCode())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //检验用户邀请码
        if (!isNullOrEmpty(registerReq.getOtherInvitationCode())){
            MmsUser mmsUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                    .eq(MmsUser::getInvitationCode,registerReq.getOtherInvitationCode()));
            if (mmsUser == null){
                return CommonResult.failed(CommonCodeEnum.USER_INVITATION_CODE_NOT_EXIST);
            }
        }


        String checkTel = "CP_" + registerReq.getTel();
        if (!cacheUtil.hasKey(checkTel)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        String code = cacheUtil.getObject(checkTel, String.class);
        if (registerReq.getCheckCode().equals(code)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        MmsUser usernameUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .eq(MmsUser::getUsername, registerReq.getUsername()));
        if (usernameUser != null) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_EXIST);
        }

        MmsUser telUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .eq(MmsUser::getTel, registerReq.getTel()));
        if (telUser != null) {
            return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
        }

        MmsUser addUser = new MmsUser();
        addUser.setUserType(USER_TYPE_NORMAL);
        addUser.setTel(registerReq.getTel());
        addUser.setPassword(USER_DEFAULT_PASSWORD);
        addUser.setUsername(USER_DEFAULT_TEXT + registerReq.getTel());
        addUser.setAuthStatus(AUTH_STATUS_NOT_AUTH);
        addUser.setQualificationType(QUALIFICATION_TYPE_NONE);
        addUser.setNickName(USER_DEFAULT_NICK_NAME);
        addUser.setOtherInvitationCode(registerReq.getOtherInvitationCode());

        mmsUserMapper.insert(addUser);

        MmsUserResp mmsUserResp = new MmsUserResp();
        BeanUtils.copyProperties(addUser, mmsUserResp);
        String token = jwtTokenUtil.generateToken(addUser.getId());
        mmsUserResp.setToken(token);
        mmsUserResp.setTokenHead(tokenHead);
        return CommonResult.success(mmsUserResp);
    }

    @Override
    public ResponseResult getUserList(Integer userType, String searchStr, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<MmsUser> queryWrapper = new LambdaQueryWrapper<>();
        if (!isNullOrEmpty(userType)) {
            queryWrapper.eq(MmsUser::getUserType, userType);
        }
        if (!isNullOrEmpty(searchStr)) {
            queryWrapper.and(wrapper -> {
                wrapper.like(MmsUser::getUsername, searchStr)
                        .or()
                        .like(MmsUser::getTel, searchStr)
                        .or()
                        .like(MmsUser::getNickName, searchStr);
            });
        }
        queryWrapper.orderByDesc(MmsUser::getCreateTime);
        Page<MmsUser> page = new Page<>(pageNum, pageSize);
        mmsUserMapper.selectPage(page, queryWrapper);
        List<MmsUserinfoResp> list = page.getRecords()
                .stream()
                .map(user -> {
                    MmsUserinfoResp mmsUserinfoResp = new MmsUserinfoResp();
                    BeanUtils.copyProperties(user, mmsUserinfoResp);
                    return mmsUserinfoResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(list, total);
    }

    @Override
    public ResponseResult getUserDetail(String userId) {
        MmsUser mmsUser = mmsUserMapper.selectById(userId);
        if (mmsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }

        MmsUserinfoResp mmsUserinfoResp = new MmsUserinfoResp();
        BeanUtils.copyProperties(mmsUser, mmsUserinfoResp);

        //TODO 角色信息 用户认证信息
        List<MmsUserExamineResp> userExamine = mmsUserExamineMapper.selectList(new LambdaQueryWrapper<MmsUserExamine>()
                        .eq(MmsUserExamine::getUserId, mmsUser.getId()))
                .stream()
                .map(examine -> {
                    MmsUserExamineResp userExamineResp = new MmsUserExamineResp();
                    BeanUtils.copyProperties(examine, userExamineResp);
                    return userExamineResp;
                })
                .collect(Collectors.toList());
        mmsUserinfoResp.setExamineList(userExamine);

        //角色信息
        List<MmsRoleResp> roleList;
        List<String> roleIDList = mmsUserRoleRelationMapper.selectList(new LambdaQueryWrapper<MmsUserRoleRelation>()
                        .eq(MmsUserRoleRelation::getUserId, userId))
                .stream()
                .map(MmsUserRoleRelation::getRoleId)
                .collect(Collectors.toList());
        if (roleIDList.size()>0){
            roleList = mmsRoleMapper.selectList(new LambdaQueryWrapper<MmsRole>()
                    .in(MmsRole::getId,roleIDList))
                    .stream()
                    .map(role->{
                        MmsRoleResp roleResp = new MmsRoleResp();
                        BeanUtils.copyProperties(role,roleResp);
                        return roleResp;
                    })
                    .collect(Collectors.toList());
            mmsUserinfoResp.setRoleList(roleList);
        }
        return CommonResult.success(mmsUserinfoResp);
    }

    @Override
    public ResponseResult addUser(MmsUserReq mmsUserReq) {
        if (isNullOrEmpty(mmsUserReq.getUserType(),
                mmsUserReq.getTel(), mmsUserReq.getUsername(),
                mmsUserReq.getPassword(), mmsUserReq.getIsAuth(),
                mmsUserReq.getQualificationType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsUser usernameUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .eq(MmsUser::getUsername, mmsUserReq.getUsername()));
        if (usernameUser != null) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_EXIST);
        }

        MmsUser telUser = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                .eq(MmsUser::getTel, mmsUserReq.getTel()));
        if (telUser != null) {
            return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
        }
        String randomStr = RandomUtils.randomNumberString(6);
        String nickName = "用户" + randomStr;

        MmsUser addUser = new MmsUser();
        addUser.setUsername(mmsUserReq.getUsername());
        addUser.setPassword(mmsUserReq.getPassword());
        addUser.setTel(mmsUserReq.getTel());
        addUser.setNickName(isNullOrEmpty(mmsUserReq.getNickName()) ? nickName : mmsUserReq.getNickName());
        addUser.setUserProfile(mmsUserReq.getUserProfile());
        addUser.setQualificationType(mmsUserReq.getQualificationType());
        addUser.setUserType(mmsUserReq.getUserType());
        addUser.setAuthStatus(mmsUserReq.getIsAuth() == IS_AUTH_FALSE ? AUTH_STATUS_NOT_AUTH : AUTH_STATUS_AUTH);
        mmsUserMapper.insert(addUser);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateUser(MmsUserReq mmsUserReq) {
        if (isNullOrEmpty(mmsUserReq.getId(), mmsUserReq.getUsername(),
                mmsUserReq.getTel(),
                mmsUserReq.getNickName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsUser mmsUser = mmsUserMapper.selectById(mmsUserReq.getId());
        if (mmsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }

        if (!mmsUser.getUsername().equals(mmsUserReq.getUsername())) {
            MmsUser user = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                    .eq(MmsUser::getUsername, mmsUserReq.getUsername()));
            if (user != null) {
                return CommonResult.failed(CommonCodeEnum.ACCOUNT_EXIST);
            }
        }

        if (!mmsUser.getTel().equals(mmsUserReq.getTel())) {
            MmsUser user = mmsUserMapper.selectOne(new LambdaQueryWrapper<MmsUser>()
                    .eq(MmsUser::getTel, mmsUserReq.getTel()));
            if (user != null) {
                return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
            }
        }

        MmsUser updateUser = new MmsUser();
        updateUser.setId(mmsUserReq.getId());
        updateUser.setUsername(mmsUserReq.getUsername());
        updateUser.setPassword(isNullOrEmpty(mmsUserReq.getPassword()) ? null : mmsUserReq.getPassword());
        updateUser.setTel(mmsUserReq.getTel());
        updateUser.setNickName(mmsUserReq.getNickName());
        updateUser.setUserProfile(mmsUserReq.getUserProfile());
        mmsUserMapper.updateById(updateUser);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateUserProfile(MmsUserReq mmsUserReq, String userId) {
        if (isNullOrEmpty(mmsUserReq.getUserProfile())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsUser updateUser = new MmsUser();
        updateUser.setId(userId);
        updateUser.setUserProfile(mmsUserReq.getUserProfile());

        mmsUserMapper.updateById(updateUser);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateUserNickName(MmsUserReq mmsUserReq, String userId) {
        if (isNullOrEmpty(mmsUserReq.getNickName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsUser updateUser = new MmsUser();
        updateUser.setId(userId);
        updateUser.setNickName(mmsUserReq.getNickName());

        mmsUserMapper.updateById(updateUser);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateUserRole(UserRoleReq userRoleReq) {
        if (isNullOrEmpty(userRoleReq.getRoleId(), userRoleReq.getUserId(),
                userRoleReq.getStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (userRoleReq.getStatus().equals(ROLE_BIND_ADD)) {
            MmsUserRoleRelation userRoleRelation = mmsUserRoleRelationMapper.selectOne(new LambdaQueryWrapper<MmsUserRoleRelation>()
                    .eq(MmsUserRoleRelation::getRoleId, userRoleReq.getRoleId())
                    .eq(MmsUserRoleRelation::getUserId, userRoleReq.getUserId()));
            if (userRoleRelation != null) {
                return CommonResult.success();
            }
            MmsUserRoleRelation addRelation = new MmsUserRoleRelation();
            addRelation.setUserId(userRoleReq.getUserId());
            addRelation.setRoleId(userRoleReq.getRoleId());
            mmsUserRoleRelationMapper.insert(addRelation);
        } else if (userRoleReq.getStatus().equals(ROLE_BIND_DELETE)) {
            mmsUserRoleRelationMapper.delete(new LambdaQueryWrapper<MmsUserRoleRelation>()
                    .eq(MmsUserRoleRelation::getRoleId, userRoleReq.getRoleId())
                    .eq(MmsUserRoleRelation::getUserId, userRoleReq.getUserId()));
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getUserInfo(String userId) {
        MmsUser mmsUser = this.getById(userId);
        if (mmsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }

        MmsUserResp mmsUserResp = new MmsUserResp();
        BeanUtils.copyProperties(mmsUser, mmsUserResp);

        String token = jwtTokenUtil.generateToken(mmsUser.getId());
        mmsUserResp.setToken(token);
        mmsUserResp.setTokenHead(tokenHead);
        return CommonResult.success(mmsUserResp);
    }

    @Override
    public ResponseResult generateSelfInvitationCode(String userId) {
        MmsUser mmsUser = mmsUserMapper.selectById(userId);
        if (!isNullOrEmpty(mmsUser.getInvitationCode())){
            return CommonResult.failed(CommonCodeEnum.USER_INVITATION_CODE_EXIST);
        }

        String code = invitationCodeUtil.generateInvitationCode();
        MmsUser updateUser = new MmsUser();
        updateUser.setId(userId);
        updateUser.setInvitationCode(code);
        mmsUserMapper.updateById(updateUser);
        return CommonResult.success(code);
    }


}
